import React, { useState, useEffect, useCallback } from 'react';
import { Droplets, Thermometer, Wind, Eye, MapPin, Clock, Waves, FlagTriangleLeft } from 'lucide-react';

interface StationData {
  id: string;
  name: string; // 测站名称（stnm）
  river: string; // 河流名称（rvnm）
  addvcd: string; // 行政区域
  currentLevel: number; // 当前水位（z）
  warningLevel: number; // 警戒水位（wrz）
  guaranteeLevel: number; // 保证水位（grz）
  tm: string; // tm
  longitude: number;
  latitude: number;
  height: number; // UI 用到的水位背景高度
  hasData?: boolean; // 是否有数据

  // 接口返回的完整字段
  frgrd?: string; //
  hnnm?: string; // 水系名称
  ogrsw?: number; // 超保证水位(米)
  q?: any; //
  stcd?: string; // 测站编码
  sttp?: string; //
  sw?: number; // 超警戒水位（米）
  usfl?: string; //
  wptn?: string; // 水势
}

// 运行时从主进程配置加载站点及拉取周期
declare global {
  interface Window {
    electronAPI?: any;
  }
}

// 自动滚动自定义Hook - 移到组件外部
const useAutoScroll = (scrollRef: React.RefObject<HTMLDivElement>, scrollSpeed: number = 50, enabled: boolean = true) => {
  useEffect(() => {
    if (!enabled) return;
    
    // console.log('useAutoScroll scrollRef =>', scrollRef.current);
    
    const element = scrollRef.current;
    if (!element) return;

    let scrollPosition = 0;
    let scrollDirection = 1; // 1: 向下, -1: 向上
    let animationId: number;

    const scroll = () => {
      if (!element) return;
      
      const maxScroll = element.scrollHeight - element.clientHeight;
      
      // 如果内容高度小于容器高度，不需要滚动
      if (maxScroll <= 0) {
        return;
      }

      // 更新滚动位置
      scrollPosition += scrollDirection * scrollSpeed / 60; // 60fps

      // console.log('滚动位置：scrollPosition =>', scrollPosition,'maxScroll =>',maxScroll);

      // 到达底部，改变方向为向上
      if (scrollPosition >= maxScroll) {
        scrollPosition = maxScroll;
        scrollDirection = -1;
        // 在底部暂停1秒
        setTimeout(() => {}, 1000);
      }
      // 到达顶部，改变方向为向下
      else if (scrollPosition <= 0) {
        scrollPosition = 0;
        scrollDirection = 1;
        // 在顶部暂停1秒
        setTimeout(() => {}, 1000);
      }

      element.scrollTop = scrollPosition;
      animationId = requestAnimationFrame(scroll);
    };

    // 开始滚动
    animationId = requestAnimationFrame(scroll);

    // 鼠标悬停时暂停滚动
    const handleMouseEnter = () => {
      cancelAnimationFrame(animationId);
    };

    const handleMouseLeave = () => {
      animationId = requestAnimationFrame(scroll);
    };

    element.addEventListener('mouseenter', handleMouseEnter);
    element.addEventListener('mouseleave', handleMouseLeave);

    return () => {
      cancelAnimationFrame(animationId);
      element.removeEventListener('mouseenter', handleMouseEnter);
      element.removeEventListener('mouseleave', handleMouseLeave);
    };
  }, [scrollRef, scrollSpeed, enabled]);
};

function App() {

  // 创建滚动引用
  const warningScrollRef = React.useRef<HTMLDivElement>(null);
  const guaranteeScrollRef = React.useRef<HTMLDivElement>(null);
  const [currentStationIndex, setCurrentStationIndex] = useState(0);
  const [isPaused, setIsPaused] = useState(false);
  const [stations, setStations] = useState<StationData[]>([]);
  const [online, setOnline] = useState<boolean>(window.electronAPI ? window.electronAPI.onlineStatus() : navigator.onLine);
  const [fetchIntervalMinutes, setFetchIntervalMinutes] = useState<number>(10);
  const [autoScrollEnabled, setAutoScrollEnabled] = useState(false); // 控制自动滚动是否启用

  // 在组件顶层调用Hook，而不是在useEffect中
  useAutoScroll(warningScrollRef, 30, autoScrollEnabled); // 滚动速度30px/s，只在enabled为true时执行
  useAutoScroll(guaranteeScrollRef, 30, autoScrollEnabled);

  // 延迟启动自动滚动，确保DOM已渲染
  useEffect(() => {
    const timer = setTimeout(() => {
      console.log('延迟启动自动滚动');
      if (warningScrollRef.current) {
        console.log('warningScrollRef.current is ready');
      }
      if (guaranteeScrollRef.current) {
        console.log('guaranteeScrollRef.current is ready');
      }
      // 启用自动滚动
      setAutoScrollEnabled(true);
    }, 1000); // 延迟1秒启动
    return () => {
      clearTimeout(timer);
      setAutoScrollEnabled(false);
    };
  }, []);

  // 将主进程缓存数据应用到渲染端状态
  const applyLatestStations = useCallback((items: any[]) => {
    if (!Array.isArray(items)) return;
    const mapped: StationData[] = items.map((it: any, idx: number) => ({
      id: String(idx + 1),
      name: String(it.name || ''),
      river: String(it.river || ''),
      addvcd: String(it.addvcd || ''),
      currentLevel: Number(it.currentLevel) || 0,
      warningLevel: Number(it.warningLevel) || 0,
      guaranteeLevel: Number(it.guaranteeLevel) || 0,
      tm: String(it.tm || ''),
      longitude: 0,
      latitude: 0,
      height: Number(it.height) || 700,
      hasData: Boolean(it.hasData),

      // 新增的接口字段
      frgrd: String(it.frgrd || ''),
      hnnm: String(it.hnnm || ''),
      ogrsw: Number(it.ogrsw) || 0,
      q: it.q,
      stcd: String(it.stcd || ''),
      sttp: String(it.sttp || ''),
      sw: Number(it.sw) || 0,
      usfl: String(it.usfl || ''),
      wptn: String(it.wptn || '')
    }));
    setStations(mapped);
    try {
      localStorage.setItem('stations-cache-v1', JSON.stringify(mapped));
    } catch {}
  }, []);

  // 初始化：读取配置，构建站点列表
  useEffect(() => {
    let unsubscribe: any;
    (async () => {
      try {
        if (window.electronAPI) {
          const cfg = await window.electronAPI.getConfig();
          const list = Array.isArray(cfg.stations) ? cfg.stations : [];

          console.log('list =>', list);

          // 先尝试读取缓存
          const cacheRaw = localStorage.getItem('stations-cache-v1');
          const cache = cacheRaw ? JSON.parse(cacheRaw) : null;
          const cacheMap: Record<string, any> = Array.isArray(cache) ? Object.fromEntries(cache.map((c: any) => [(`${c.river}|${c.name}`), c])) : {};

          const initStations: StationData[] = list.map((s: any, idx: number) => {
            const key = `${s.hlname}|${s.czname}`;
            const cached = cacheMap[key];
            return {
              id: String(idx + 1),
              name: s.czname,
              river: s.hlname,
              addvcd: cached.addvcd,
              currentLevel: Number(cached?.z) || 0,
              warningLevel: Number(cached?.sw) || 0,
              guaranteeLevel: Number(cached?.grz) || 0,
              tm: String(cached?.tm || ''),
              longitude: 0,
              latitude: 0,
              height: Number(s.height) || 700,
              hasData: Boolean(cached && typeof cached.z === 'number'),

              // 新增的接口字段（初始化时没有实际数据，使用默认值）
              frgrd: '',
              hnnm: '',
              ogrsw: 0,
              q: null,
              stcd: '',
              sttp: '',
              sw: 0,
              usfl: '',
              wptn: ''
            };
          });
          setStations(initStations);
          setFetchIntervalMinutes(Number(cfg.fetchIntervalMinutes) || 10);
        }
      } catch {
        // ignore
      }
    })();

    if (window.electronAPI) {
      unsubscribe = window.electronAPI.subscribeOnline((flag: boolean) => setOnline(flag));
    } else {
      const listener = () => setOnline(navigator.onLine);
      window.addEventListener('online', listener);
      window.addEventListener('offline', listener);
      unsubscribe = () => {
        window.removeEventListener('online', listener);
        window.removeEventListener('offline', listener);
      };
    }

    return () => {
      if (unsubscribe) unsubscribe();
    };
  }, []);

  // 注册托盘刷新事件：触发主进程批量拉取，然后读取缓存应用
  useEffect(() => {
    if (!window.electronAPI) return;
    const off = window.electronAPI.onRefreshNow(() => {
      try { alert('收到托盘指令：开始同步更新数据'); } catch {}
      try { window.electronAPI.writeLog('info', 'renderer.refresh_now'); } catch {}
      (async () => {
        try {
          await window.electronAPI.fetchAllStationsNow();
        } catch {}
        try {
          const latest = await window.electronAPI.getLatestStations();
          if (latest?.ok) applyLatestStations(latest.items || []);
        } catch {}
      })();
    });
    return () => { if (off) off(); };
  }, [applyLatestStations]);

  // 定时从主进程缓存读取
  useEffect(() => {
    if (!window.electronAPI) return;

    const readLatest = async () => {
      try {
        const latest = await window.electronAPI.getLatestStations();
        console.log('getLatestStations latest =>', latest);
        if (latest?.ok) applyLatestStations(latest.items || []);
      } catch {}
    };

    // 立即读取一次
    readLatest();
    const ms = Math.max(1, fetchIntervalMinutes) * 60 * 1000;
    const timer = setInterval(readLatest, ms);
    return () => { clearInterval(timer); };
  }, [fetchIntervalMinutes, applyLatestStations]);

  const currentStation = stations[currentStationIndex] || {
    id: '0',
    name: '',
    river: '',
    addvcd: '',
    currentLevel: 0,
    warningLevel: 0,
    guaranteeLevel: 0,
    tm: '',
    longitude: 0,
    latitude: 0,
    height: 700,
    // 新增的接口字段（默认值）
    frgrd: '',
    hnnm: '',
    ogrsw: 0,
    q: null,
    stcd: '',
    sttp: '',
    sw: 0,
    usfl: '',
    wptn: ''
  } as StationData;

  console.log('currentStation =>', currentStation);

  // 判断警告级别
  const getWarningLevel = (current: number, warning: number, guarantee: number) => {
    if (current <= 0 ||  guarantee <= 0 || warning <= 0) return 'normal';
    if (current >= guarantee) return 'guarantee';
    if (current >= warning) return 'warning';
    return 'normal';
  };

  const warningLevel = getWarningLevel(
    currentStation.currentLevel,
    currentStation.warningLevel,
    currentStation.guaranteeLevel
  );

  // 自动轮播（空数组保护）
  useEffect(() => {
    if (isPaused || stations.length === 0) return;
    const interval = setInterval(() => {
      setCurrentStationIndex((prev) => {
        const len = stations.length;
        if (len === 0) return 0;
        return (Number.isFinite(prev) ? prev : 0) >= 0 ? (prev + 1) % len : 0;
      });
    }, 10000);
    return () => clearInterval(interval);
  }, [isPaused, stations.length]);

  // 当测站列表变化时，重置索引，避免越界/NaN
  useEffect(() => {
    if (stations.length === 0) {
      setCurrentStationIndex(0);
    } else if (!Number.isFinite(currentStationIndex) || currentStationIndex >= stations.length) {
      setCurrentStationIndex(0);
    }
  }, [stations.length]);

  const handleMouseEnter = useCallback(() => {
    // setIsPaused(true);
  }, []);

  const handleMouseLeave = useCallback(() => {
    setIsPaused(false);
  }, []);

  // 计算水位百分比
  const calculateWaterPercentage = (current: number, warning: number, guarantee: number) => {
    if (!guarantee && !warning) return 50;
    const safeGuarantee = guarantee || (warning + 2);
    const max = safeGuarantee + 3; // 超出保证水位3米为满刻度
    const min = Math.min(current, warning || current) - 8; // 最低刻度
    return Math.max(5, Math.min(95, ((current - min) / (max - min)) * 100));
  };

  const waterPercentage = calculateWaterPercentage(
    currentStation.currentLevel,
    currentStation.warningLevel,
    currentStation.guaranteeLevel
  );

    // 动态计算刻度线范围和间隔
  const calculateScaleParams = () => {
    const { currentLevel, warningLevel, guaranteeLevel } = currentStation;

    // 确定最大和最小水位
    const maxLevel = Math.max(currentLevel, warningLevel, guaranteeLevel);
    const minLevel = Math.min(currentLevel, warningLevel, guaranteeLevel);

    // 添加额外的上下边界（根据水位范围动态调整）
    let extraTop = 0;
    let extraBottom = 0;

    // 根据水位范围确定额外边界
    const range = maxLevel - minLevel;
    if (range < 10) {
      extraTop = 3;
      extraBottom = 6;
    } else if (range < 50) {
      extraTop = 5;
      extraBottom = 10;
    } else if (range < 100) {
      extraTop = 10;
      extraBottom = 20;
    } else if (range < 500) {
      extraTop = 20;
      extraBottom = 40;
    } else if (range < 1000) {
      extraTop = 50;
      extraBottom = 100;
    } else {
      extraTop = 100;
      extraBottom = 200;
    }

    // 计算最终的刻度范围
    const finalMax = maxLevel + extraTop;
    const finalMin = Math.max(0, minLevel - extraBottom); // 最小值不能小于0

    // 根据范围确定刻度间隔
    let interval = 0.5;
    if (range < 10) {
      interval = 0.5;
    } else if (range < 50) {
      interval = 1;
    } else if (range < 100) {
      interval = 2;
    } else if (range < 500) {
      interval = 5;
    } else if (range < 1000) {
      interval = 10;
    } else {
      interval = 20;
    }

    // 计算刻度数量
    const count = Math.ceil((finalMax - finalMin) / interval) + 1;

    return {
      max: finalMax,
      min: finalMin,
      interval,
      count
    };
  };

  let currentHeight = 0;
  // 生成刻度线数组
  const generateScaleLines = () => {
    const { max, min, interval, count } = calculateScaleParams();
    const lines = [];

    for (let i = 0; i < count; i++) {
      const value = max - (i * interval);
      if (value >= min) {
          let line = {
              i,
              value,
              isWarning: Math.abs(value - currentStation.warningLevel) < (interval / 2),
              isGuarantee: Math.abs(value - currentStation.guaranteeLevel) < (interval / 2),
              isCurrent: Math.abs(value - currentStation.currentLevel) < (interval / 2)
          }
        lines.push(line);

          if(line.isCurrent){
              let generate=  max === min ? 0 : ((max - value) / (max - min))
              currentHeight = 2568-2568*generate;
            console.log('generate',generate,currentHeight);
          }
      }
    }

    return lines;
  };

  const scaleLines = generateScaleLines();

  return (
    <div
      className="min-h-screen w-full relative overflow-hidden bg-gradient-to-br from-slate-900 via-blue-900 to-slate-800"
      onMouseEnter={handleMouseEnter}
      onMouseLeave={handleMouseLeave}
    >
      {/* 高德地图背景 */}
      <div className="absolute inset-0 opacity-20">
        <img src="./map.png" className="w-full h-full"></img>
      </div>
      {/* 河水背景效果 */}
      <div className="absolute inset-0 water-background wave-content">
        <div className="wave"></div>
        <div className="wave-bg" style={{height:currentHeight+'px'}}></div>
      </div>
      {/* 河水背景效果 */}
       {/*<div className="absolute inset-0 water-background">
        <div className="absolute inset-0 bg-gradient-to-t from-blue-900/30 via-blue-800/20 to-transparent">
          <div className="wave-layer wave-layer-1"></div>
          <div className="wave-layer wave-layer-2"></div>
          <div className="wave-layer wave-layer-3"></div>
          <div className="wave-layer wave-layer-4"></div>
        </div>
      </div>*/}

      {/* 网络状态与警告边框动画 */}
      {/* 右上角网络状态指示：在线绿色，离线红色 */}
      <div className="absolute right-4 top-4 z-50 flex items-center gap-2">
        <div className={`w-3 h-3 rounded-full ${online ? 'bg-green-400' : 'bg-red-500'}`}></div>
      </div>

      {(warningLevel === 'warning' || warningLevel === 'guarantee') && (
        <>
          <div className={`absolute inset-0 z-40 ${
            warningLevel === 'guarantee' ? 'cockpit-red' : 'cockpit-warning'
          } warning-border-pulse pointer-events-none`} />
          {/* <div className={`absolute inset-4 border-4 ${
            warningLevel === 'guarantee' ? 'border-red-400' : 'border-yellow-400'
          } warning-border-pulse-inner pointer-events-none`} /> */}

        </>
      )}

      {/* 动态背景效果 */}
      <div className="absolute inset-0 overflow-hidden pointer-events-none">
        {/* 粒子效果 */}
        <div className="absolute inset-0">
          {Array.from({ length: 60 }).map((_, i) => (
            <div
              key={i}
              className="absolute -top-6 w-4 h-4 bg-cyan-400/20 rounded-full particle-float"
              style={{
                left: `${Math.random() * 100}%`,
                animationDelay: `${Math.random() * 10}s`,
                animationDuration: `${8 + Math.random() * 6}s`
              }}
            />
          ))}
        </div>

        {/* 光线效果  */}
        {/* <div className="absolute inset-0">
          <div className="absolute top-1/4 left-0 w-full h-px bg-gradient-to-r from-transparent via-cyan-400/50 to-transparent light-sweep"></div>
          <div className="absolute top-1/2 left-0 w-full h-px bg-gradient-to-r from-transparent via-blue-400/50 to-transparent light-sweep" style={{ animationDelay: '3s' }}></div>
          <div className="absolute top-3/4 left-0 w-full h-px bg-gradient-to-r from-transparent via-cyan-300/50 to-transparent light-sweep" style={{ animationDelay: '6s' }}></div>
        </div> */}
      </div>

<div className='h-full  flex flex-col'>
        {/* 顶部标题区域 */}
        <div className="relative pt-20 pb-10 px-16">
          <div className="text-center mb-10">
            <div className="flex items-center justify-center mb-8">
              <div className="h-1 w-32 bg-gradient-to-r from-transparent via-cyan-400 to-transparent glow-line"></div>
              <div className="mx-8 relative">
                <Waves className="text-cyan-400 drop-shadow-2xl" size={64} />
                <div className="absolute inset-0 bg-cyan-400/20 rounded-full blur-xl animate-pulse"></div>
              </div>
              <div className="h-1 w-32 bg-gradient-to-r from-transparent via-cyan-400 to-transparent glow-line"></div>
            </div>
            <h1 className="text-6xl font-bold text-white mb-6 tracking-wider drop-shadow-2xl">
              水情监测系统
            </h1>
            <div className="text-3xl text-cyan-300 tracking-widest opacity-90">
              WATER LEVEL MONITORING SYSTEM
            </div>
          </div>

          {/* 重点站点 */}
          <div className="">
            <div className="glass-card p-10 border border-cyan-500/30 shadow-2xl card-glow">
              <h2 className="text-3xl font-bold text-white mb-6 flex items-center">
                <Eye className="mr-6 text-cyan-400" size={48} />
                重点站点
              </h2>
                <div className="mb-6">
                  <table className="w-full">
                    <thead>
                      <tr className="border-b border-white/10">
                        <th className="text-left pb-4 text-2xl text-gray-300 font-medium">站点名称</th>
                        <th className="text-left pb-4 text-2xl text-gray-300 font-medium">当前水位</th>
                        <th className="text-left pb-4 text-2xl text-gray-300 font-medium">超警戒</th>
                        <th className="text-left pb-4 text-2xl text-gray-300 font-medium">超保证</th>
                        <th className="text-left pb-4 text-2xl text-gray-300 font-medium">其他</th>
                      </tr>
                    </thead>
                    <tbody>
                    {stations.filter(a=>a.name=='寸滩' || a.name=='磁器口').map((stationData, index) => (
                      <tr className="border-b border-white/5 hover:bg-white/5 transition-colors">
                        <td className="text-left py-4 text-2xl font-bold text-white drop-shadow-lg">{stationData.name}</td>
                        <td className="text-left py-4 text-3xl font-bold text-green-400 drop-shadow-lg"> {stationData.hasData ? `${stationData.currentLevel.toFixed(2)}米` : '无数据'}</td>
                        <td className="text-left py-4 text-2xl text-yellow-400">{stationData.sw}米</td>
                        <td className="text-left py-4 text-2xl text-red-400">{stationData.ogrsw}米</td>
                        <td className="text-left py-4 text-2xl text-blue-200 space-y-2">
                          {/* <div>所属河流：{stationData.river || '—'}</div>
                          <div>行政区域：{stationData.addvcd || '—'}</div> */}
                          <div>更新时间：{stationData.tm || (stationData.hasData === false ? '无数据' : '')}</div>
                        </td>
                      </tr>
                        ))
                    }
                    </tbody>
                  </table>
                </div>

              <h2 className="text-3xl font-bold text-white mb-6 flex items-center">
                <Waves className="mr-6 text-red-400" size={48} />
                预警站点
              </h2>
              
              {/* 统计信息 */}
              <div className="grid grid-cols-2 gap-8">
                <div className="glass-item p-4 text-center">
                  <div className="text-2xl text-yellow-400 mb-2">超警戒站点</div>
                  <div className="text-3xl font-bold text-yellow-400">
                    {stations.filter(s => s.sw > 0 && s.ogrsw<=0).length}
                  </div>

                  {/* 超警戒站点 */}
                  {(() => {
                    const warningStations = stations.filter(s => s.sw > 0 && s.ogrsw<=0);
                    return warningStations.length > 0 ? (
                        <div>
                          <div className="p-2 overflow-hidden">
                            <div className="space-y-2 h-[110px] overflow-hidden">
                              <div  ref={warningScrollRef} className="space-y-2 h-[110px] overflow-y-auto custom-scrollbar">
                                <div>
                                  {warningStations.map((station, index) => (
                                      <div key={`warning-${index}`} className="flex justify-between items-center py-2 border-b border-yellow-400/20">
                                        <span className="text-2xl text-white font-medium">{station.name}</span>
                                        <span className="text-xl text-yellow-400">超警戒 {station.sw}米</span>
                                      </div>
                                  ))}
                                </div>
                              </div>
                            </div>
                          </div>
                        </div>
                    ) : <div className="text-center py-6">
                      <div className="text-3xl text-green-400 font-medium">暂无预警站点</div>
                      <div className="text-xl text-gray-400 mt-2">所有站点水位均在正常范围内</div>
                    </div>;
                  })()}
                </div>
                <div className="glass-item p-4 text-center">
                  <div className="text-2xl text-red-400 mb-2">超保证站点</div>
                  <div className="text-3xl font-bold text-red-400">
                    {stations.filter(s => s.ogrsw > 0).length}
                  </div>

                  {/* 超保证站点 */}
                  {(() => {
                    const guaranteeStations = stations.filter(s => s.ogrsw > 0);
                    return guaranteeStations.length > 0 ? (
                        <div>
                          <div className="p-2 overflow-hidden">
                            <div ref={guaranteeScrollRef} className="space-y-2 h-[110px] overflow-y-auto custom-scrollbar">
                              <div>
                                {guaranteeStations.map((station, index) => (
                                    <div key={`guarantee-${index}`} className="flex justify-between items-center py-2 border-b border-red-400/20">
                                      <span className="text-2xl text-white font-medium">{station.name}</span>
                                      <span className="text-xl text-red-400">超保证 {station.ogrsw}米</span>
                                    </div>
                                ))}
                              </div>
                            </div>
                          </div>
                        </div>
                    ) : <div className="text-center py-6">
                      <div className="text-3xl text-green-400 font-medium">暂无预警站点</div>
                      <div className="text-xl text-gray-400 mt-2">所有站点水位均在正常范围内</div>
                    </div>;
                  })()}
                </div>
              </div>
            </div>
          </div>
        </div>
      {/* 主要内容区域 */}
      <div className="relative z-10 h-full flex flex-col pr-40">

        {/* 右侧水位刻度尺 */}
        <div className="absolute right-0 top-0 h-full w-24 bg-gradient-to-l from-black/40 to-transparent backdrop-blur-sm">
          <div className="relative h-full flex flex-col p-4">
            <div className="text-cyan-400 text-2xl font-bold mb-4 writing-vertical-rl text-center">水位刻度(米)</div>

            {/* 刻度线 */}
            <div className="relative h-full mt-16">
              {scaleLines.map((line, index) => {
                const { value, isWarning, isGuarantee, isCurrent } = line;
                // 计算在刻度线中的位置百分比
                const { max, min } = calculateScaleParams();
                const positionPercentage = max === min ? 0 : ((max - value) / (max - min)) * 100;

                return (
                    <div
                        key={index}
                        className={`absolute right-0 flex items-center transition-all duration-500 ${
                            isCurrent ? 'z-10' : 'z-0'
                        }`}
                        style={{ top: `${positionPercentage}%` }}
                    >
                      {/* 当前水位特殊背景 */}
                      {isCurrent && (
                          <>
                            <div className="absolute -left-4 -right-8 -top-3 -bottom-3 bg-purple-400/20 rounded-lg animate-pulse">
                              <FlagTriangleLeft className="text-purple-400 drop-shadow-2xl flag-icon" size={64} />
                            </div>
                            <div className="absolute -left-2 -right-6 -top-2 -bottom-2 bg-purple-400/30 rounded-md"></div>
                          </>
                      )}

                      <div className={`h-8 items-center flex ${
                          isGuarantee ? 'w-20 bg-red-400' :
                              isWarning ? 'w-20 bg-yellow-400' :
                                  isCurrent ? 'w-20 bg-purple-400 shadow-lg shadow-purple-400/50' :
                                      index % 2 === 0 ? 'w-20 bg-gray-400' : 'w-16 bg-gray-600'
                      } relative z-10`}>
                        {isCurrent && (
                            <>
                              <div className="absolute inset-0 bg-purple-400 animate-pulse"></div>
                              <div className="absolute -inset-1 bg-purple-400/50 blur-sm"></div>
                            </>
                        )}
                        <div className="text-center flex-1"><b>{isWarning?'超警戒线':isGuarantee?'超保证线':''}</b></div>
                      </div>

                      <div className={`ml-2 text-4xl font-bold ${
                          isGuarantee ? 'text-red-400 font-bold text-shadow' :
                              isWarning ? 'text-yellow-400 font-bold text-shadow' :
                                  isCurrent ? 'text-purple-400 font-bold text-4lg drop-shadow-lg animate-pulse' :
                                      'text-gray-300'
                      } relative z-10`}>
                        {value.toFixed(1)}
                        {isCurrent && (
                            <>
                              <div className="absolute inset-0 text-purple-100">{value.toFixed(1)}</div>
                              {/*<span className="ml-1 text-lg text-purple-100 animate-bounce">●</span>*/}
                            </>
                        )}
                      </div>
                    </div>
                );
              })}
            </div>
          </div>
        </div>

        {/* 站点信息区域 */}
        <div className="flex-1 px-16 pb-20 pl-15">
          <div className="glass-card p-10 border border-cyan-500/30 card-glow site-bg">
            <h3 className="text-5xl font-bold text-white mb-16 flex items-center">
              <MapPin className="mr-6 text-cyan-400" size={48} />
              站点信息
            </h3>

            <div className="grid grid-cols-1 gap-12 mb-16">
              <div className="glass-item p-8">
                <div className="text-3xl text-gray-300 mb-8">站点名称</div>
                <div className="text-6xl font-bold text-white drop-shadow-lg">{currentStation.name || '—'}</div>
              </div>

              <div className="glass-item p-8">
                <div className="text-3xl text-gray-300 mb-8">所属河流</div>
                <div className="text-6xl font-bold text-blue-300 drop-shadow-lg">{currentStation.river || '—'}</div>
              </div>

              <div className="glass-item p-8">
                <div className="text-3xl text-gray-300 mb-8">行政区域</div>
                <div className="text-6xl font-bold text-white drop-shadow-lg">{currentStation.addvcd || '—'}</div>
              </div>

              <div className="glass-item p-8 flex items-center">
                {/* <Clock className="mr-6 text-gray-400" size={36} /> */}
                <div>
                  <div className="text-3xl text-gray-300 mb-8">更新时间</div>
                  <div className="text-4xl text-white">{currentStation.tm || (currentStation.hasData === false ? '无数据' : '')}</div>
                </div>
              </div>
            </div>

            {/* 水位数据 */}
            <div className="space-y-8">
              <h4 className="text-4xl font-bold text-white mb-8">水位数据</h4>

              <div className="glass-item p-8 flex justify-between items-center">
                <span className="text-4xl text-gray-300">当前水位</span>
                <span className={`text-4xl font-bold drop-shadow-lg ${
                  warningLevel === 'guarantee' ? 'text-red-400' :
                  warningLevel === 'warning' ? 'text-yellow-400' : 'text-green-400'
                }`}>
                  {currentStation.hasData ? `${currentStation.currentLevel.toFixed(2)}米` : '无数据'}
                </span>
              </div>

              {/*  <div className="glass-item p-8 flex justify-between items-center">
                <span className="text-4xl text-gray-300">警戒水位</span>
                <span className="text-6xl font-bold text-yellow-400 drop-shadow-lg">
                  {currentStation.warningLevel.toFixed(2)}m
                </span>
              </div>
              
              <div className="glass-item p-8 flex justify-between items-center">
                <span className="text-4xl text-gray-300">保证水位</span>
                <span className="text-6xl font-bold text-red-400 drop-shadow-lg">
                  {currentStation.guaranteeLevel.toFixed(2)}m
                </span>
              </div> */}

              <div className="glass-item p-8 flex justify-between items-center">
                <span className="text-4xl text-gray-300">超警戒</span>
                <span className={`text-5xl font-bold drop-shadow-lg ${
                  currentStation.currentLevel > currentStation.warningLevel ? 'text-yellow-400' : 'text-wihte'
                }`}>
                  {currentStation.sw}米
                </span>
              </div>

              <div className="glass-item p-8 flex justify-between items-center">
                <span className="text-4xl text-gray-300">超保证</span>
                <span className={`text-5xl font-bold drop-shadow-lg ${
                  currentStation.currentLevel > currentStation.guaranteeLevel ? 'text-red-400' : 'text-wihte'
                }`}>
                  {currentStation.ogrsw}米
                </span>
              </div>
            </div>
          </div>
        </div>
      </div>
</div>
        {/*  底部指示器 */}
        <div className="px-16 pb-12 absolute footer-dot text-center">
          <div className="flex justify-center space-x-4">
            {stations.map((_, index) => (
              <div
                key={index}
                onClick={() => {setCurrentStationIndex(index); try { window.electronAPI.writeLog('info', 'renderer.dot_click', { index }); } catch {}}}
                className={`relative transition-all duration-500 ${
                  index === currentStationIndex ? 'scale-150' : 'scale-100'
                }`}
              >
                <div className={`w-4 h-4 rounded-full transition-all duration-500 ${
                  index === currentStationIndex ? 'bg-cyan-400' : 'bg-blue-900'
                }`} />
                {index === currentStationIndex && (
                  <>
                    <div className="absolute inset-0 w-4 h-4 bg-cyan-400 rounded-full animate-ping"></div>
                    <div className="absolute inset-0 w-4 h-4 bg-cyan-400/50 rounded-full animate-pulse"></div>
                  </>
                )}
              </div>
            ))}
          </div>
        </div>
    </div>
  );
}

export default App;